package com.why.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.why.domain.Teacher;
import com.why.exception.BusinessException;
import com.why.service.TeacherService;
import com.why.mapper.TeacherMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
* @author 王海云
* @description 针对表【teacher】的数据库操作Service实现
* @createDate 2024-06-14 19:34:26
*/
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher>
    implements TeacherService{
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Override
    public String login(Teacher teacher) {
        Teacher teacherByDb = lambdaQuery().eq(Teacher::getUsername, teacher.getUsername())
                .eq(Teacher::getPassword, teacher.getPassword()).one();
        if (Objects.isNull(teacherByDb)) {
            throw new BusinessException("用户名或密码错误!");
        }
        // 生成UUID
        String token = UUID.randomUUID().toString();
        // 存入Redis
        redisTemplate.opsForValue().set("rh-call-name-token:" + token, teacherByDb, 48, TimeUnit.HOURS);
        return token;
    }

    @Override
    @Transactional
    public void register(Teacher teacher) {
        // 参数校验
        if (Objects.isNull(teacher.getUsername()) || Objects.isNull(teacher.getPassword())) {
            throw new BusinessException("用户名或密码不能为空!");
        }
        if (lambdaQuery().eq(Teacher::getUsername, teacher.getUsername()).count() > 0) {
            throw new BusinessException("用户名已存在!");
        }
        save(teacher);
    }
}




